package org.light.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.limitedverb.CountSearchByFieldsRecords;
import org.light.utils.DomainTokenUtil;
import org.light.utils.StringUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class SearchByFields extends Verb implements EasyUIPositions {
	protected CountSearchByFieldsRecords countSearch = new CountSearchByFieldsRecords();
	protected Set<Field> deniedFields = new TreeSet<>();

	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
			method.setNoContainer(false);
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(),new Type(this.domain.getDomainSuffix()+ "." + this.domain.getType())));
			method.addSignature(new Signature(3, "ignoreMap","map[string]bool"));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+ "." + this.domain.getType()));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			
			sList.add(new Statement(3000L,1,"query := \"select " + DomainTokenUtil.generateTableCommaFieldsWithDeniedFields(domain,this.deniedFields) + " from " + domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain)+" where 1=1 \""));
			sList.add(new Statement(4000L,0,""));
			int index = 0;
			long serial = 5000L;
			for (Field f: this.domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					if (f.getFieldType().equals("string")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" like '%\"+"+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"()+\"%' \""));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("bool")) {
						
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						if ("oracle".equalsIgnoreCase(this.domain.getDbType())){
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+utils.ParseBooltoIntStr("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"())"));
						}else {
							sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatBool("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"())"));
						}
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("int64")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatInt("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 10)"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("int32")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+fmt.Sprint("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}else if (f.getFieldType().equals("int")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.Itoa("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}else if (f.getFieldType().equals("float")||f.getFieldType().equals("float64")||f.getFieldType().equals("float32")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatFloat("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 'f', 4, 64)"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}
					serial += 5000L;
					index ++;
				}					
			}
			if (("PostgreSQL".equalsIgnoreCase(this.getDbType())||"pgsql".equalsIgnoreCase(this.getDbType()))&&this.domain.getDomainId()!=null) {
				sList.add(new Statement(serial, 1, "query += \" order by " + StringUtil.changeDomainFieldtoTableColum(domain.getDomainId().getFieldName()) + " asc \""));
				serial += 1000L;
			}	
			sList.add(new Statement(serial+3000L,0,""));
			sList.add(new Statement(serial+6000L,1,"stmt, err := db.Prepare(query)"));
			sList.add(new Statement(serial+6500L,1,"defer stmt.Close()"));
			sList.add(new Statement(serial+7000L,1,"if err != nil {"));
			sList.add(new Statement(serial+8000L,2,"panic(err)"));
			sList.add(new Statement(serial+9000L,1,"}"));
			sList.add(new Statement(serial+10000L,0,""));
			sList.add(new Statement(serial+11000L,1,"rows, err := stmt.Query()"));
			sList.add(new Statement(serial+12000L,1,"if err != nil {"));
			sList.add(new Statement(serial+13000L,2,"panic(err)"));
			sList.add(new Statement(serial+14000L,1,"}"));
			
			sList.add(new Statement(serial+15000L,1,"var "+this.domain.getLowerFirstPlural()+" [] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			sList.add(new Statement(serial+16000L,0,""));
			sList.add(new Statement(serial+17000L,1,"for rows.Next() {"));
			
			StringBuilder sb = new StringBuilder();
			if (this.domain.getDomainId()!=null) sList.add(new Statement(serial+18000L,1,"var "+this.domain.getDomainId().getLowerFirstFieldName()+" "+ this.domain.getDomainId().getFieldTypeWithParseImage()));
			if (this.domain.getDomainName()!=null) sList.add(new Statement(serial+19000L,1,"var "+this.domain.getDomainName().getLowerFirstFieldName()+" "+ this.domain.getDomainName().getFieldTypeWithParseImage()));
			if (this.domain.getActive()!=null) {
				if ("oracle".equalsIgnoreCase(this.getDbType())) sList.add(new Statement(serial+20000L,2,"var "+this.domain.getActive().getLowerFirstFieldName()+" int"));
				else sList.add(new Statement(serial+20000L,2,"var "+this.domain.getActive().getLowerFirstFieldName()+" "+ this.domain.getActive().getFieldTypeWithParseImage()));
			}
			
			if (this.domain.getDomainId()!=null) sb.append("&").append(this.domain.getDomainId().getLowerFirstFieldName()).append(",");
			if (this.domain.getDomainName()!=null) sb.append("&").append(this.domain.getDomainName().getLowerFirstFieldName()).append(",");
			if (this.domain.getActive()!=null) sb.append("&").append(this.domain.getActive().getLowerFirstFieldName()).append(",");
			serial += 21000L;			
			for (Field f:this.domain.getPlainFields()) {
				if (!deniedFields.contains(f)) {
					if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.domain.getDbType())){
						sList.add(new Statement(serial,1,"var "+f.getLowerFirstFieldName()+" NullString"));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
						continue;
					}
					if ("oracle".equalsIgnoreCase(this.getDbType())&&"bool".equals(f.getFieldType())) {
						sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" int"));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
					}else {
						sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldNullTypeWithParseImage()));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
					}
				}
			}
			String fieldsQuery = sb.toString();
			if (fieldsQuery.endsWith(",")) fieldsQuery = fieldsQuery.substring(0,fieldsQuery.length()-1);

			sList.add(new Statement(serial,0,""));
			sList.add(new Statement(serial+1000L,2,"err := rows.Scan("+fieldsQuery+")"));
			sList.add(new Statement(serial+2000L,2,"if err != nil {"));
			sList.add(new Statement(serial+3000L,3,"panic(err)"));
			sList.add(new Statement(serial+4000L,2,"}"));
			sList.add(new Statement(serial+5000L,2,"var "+this.domain.getLowerFirstDomainName()+" "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
						
			if (this.domain.getDomainId()!=null) sList.add(new Statement(serial+6000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getDomainId().getCapFirstFieldName()+"("+this.domain.getDomainId().getLowerFirstFieldName()+")"));
			if (this.domain.getDomainName()!=null) sList.add(new Statement(serial+7000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getDomainName().getCapFirstFieldName()+"("+this.domain.getDomainName().getLowerFirstFieldName()+")"));
			if (this.domain.getActive()!=null) {
				if ("oracle".equalsIgnoreCase(this.getDbType())) sList.add(new Statement(serial+8000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getActive().getCapFirstFieldName()+"(utils.ParseInttoBool("+this.domain.getActive().getLowerFirstFieldName()+"))"));
				else sList.add(new Statement(serial+8000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getActive().getCapFirstFieldName()+"("+this.domain.getActive().getLowerFirstFieldName()+")"));
			}
			serial += 9000L;
			for (Field f:this.domain.getPlainFields()) {
				if (!deniedFields.contains(f)) {
					if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.domain.getDbType())){
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullStringtoInt64("+f.getLowerFirstFieldName()+"))"));
						serial += 1000L;
						continue;
					}
					switch (f.getFieldType()) {
					case "bool": 
						if ("oracle".equalsIgnoreCase(this.domain.getDbType())) sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseInttoBool("+f.getLowerFirstFieldName()+"))"));
						else sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullBool("+f.getLowerFirstFieldName()+"))"));
						break;
					case "string": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullString("+f.getLowerFirstFieldName()+"))"));
						break;
					case "int64": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt64("+f.getLowerFirstFieldName()+"))"));
						break;
					case "float64": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullFloat64("+f.getLowerFirstFieldName()+"))"));
						break;
					case "int32": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt32("+f.getLowerFirstFieldName()+"))"));
						break;
					default:
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
					}
					serial += 1000L;
				}
			}
			sList.add(new Statement(serial,2,""+this.domain.getLowerFirstPlural()+" = append("+this.domain.getLowerFirstPlural()+", "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(serial+1000L,1,"}"));
			sList.add(new Statement(serial+2000L,1,"return "+this.domain.getLowerFirstPlural()+""));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(), this.domain.getType()));

			return method;
		}
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
			method.setReturnType(new Type("List", this.domain, this.domain.getPackageToken()));
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(), this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(2, "ignoreMap","map[string]bool"));
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(new Statement(3000L, 1, "return "+this.domain.getDaoimplSuffix()+".Search" + this.domain.getCapFirstPlural() + "ByFields(db,"
					+ this.domain.getLowerFirstDomainName() + ",ignoreMap)"));
			method.setMethodStatementList(WriteableUtil.merge(list));

			return method;
		}
	}
	public SearchByFields() {
		super();
		this.dbType = "MariaDB";
		this.setLabel("按字段搜索");
	}
	
	public SearchByFields(String dbType) {
		super();
		this.dbType = dbType;
		this.setLabel("按字段搜索");
	}

	public SearchByFields(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("SearchByFields");
		this.countSearch = new CountSearchByFieldsRecords(domain);
		this.setVerbName("search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
		this.setLabel("按字段搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByFields");
	}
	
	public SearchByFields(Domain domain,String dbType) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("SearchByFields");
		this.countSearch = new CountSearchByFieldsRecords(domain);
		this.setVerbName("search" + StringUtil.capFirst(this.domain.getPlural()) + "ByFields");
		this.setLabel("按字段搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByFields");
	}


	@Override
	public Method generateControllerMethod() throws Exception {
		return null;
	}
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		return null;
	}
	public Set<Field> getDeniedFields() {
		return deniedFields;
	}
	public void setDeniedFields(Set<Field> deniedFields) {
		this.deniedFields = deniedFields;
	}
}
